#!/usr/bin/env python3
"""
批量替换Java文件中的Swagger 2注解为OpenAPI 3注解
用于Spring Boot 2.x升级到3.x的迁移
"""
import os
import re
import sys

def replace_swagger_annotations(file_path):
    """替换文件中的Swagger注解为OpenAPI 3注解"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 替换规则
        replacements = [
            # 导入语句替换
            (r'import io\.swagger\.annotations\.Api;', 'import io.swagger.v3.oas.annotations.tags.Tag;'),
            (r'import io\.swagger\.annotations\.ApiOperation;', 'import io.swagger.v3.oas.annotations.Operation;'),
            (r'import io\.swagger\.annotations\.ApiParam;', 'import io.swagger.v3.oas.annotations.Parameter;'),
            (r'import io\.swagger\.annotations\.ApiModel;', 'import io.swagger.v3.oas.annotations.media.Schema;'),
            (r'import io\.swagger\.annotations\.ApiModelProperty;', 'import io.swagger.v3.oas.annotations.media.Schema;'),
            
            # 注解替换
            (r'@Api\s*\(\s*tags\s*=\s*"([^"]*)"[^)]*\)', r'@Tag(name = "\1")'),
            (r'@Api\s*\(\s*value\s*=\s*"([^"]*)"[^)]*\)', r'@Tag(name = "\1")'),
            (r'@ApiOperation\s*\(\s*value\s*=\s*"([^"]*)"[^)]*\)', r'@Operation(summary = "\1")'),
            (r'@ApiOperation\s*\(\s*"([^"]*)"[^)]*\)', r'@Operation(summary = "\1")'),
            (r'@ApiParam\s*\(\s*value\s*=\s*"([^"]*)"[^)]*\)', r'@Parameter(description = "\1")'),
            (r'@ApiModel\s*\(\s*value\s*=\s*"([^"]*)"[^)]*\)', r'@Schema(description = "\1")'),
            (r'@ApiModelProperty\s*\(\s*value\s*=\s*"([^"]*)"[^)]*\)', r'@Schema(description = "\1")'),
        ]
        
        # 执行替换
        for pattern, replacement in replacements:
            content = re.sub(pattern, replacement, content, flags=re.MULTILINE | re.DOTALL)
        
        # 如果有更改，写回文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 更新: {file_path}")
            return True
        else:
            return False
            
    except Exception as e:
        print(f"✗ 错误处理文件 {file_path}: {e}")
        return False

def process_directory(directory):
    """处理目录中的所有Java文件"""
    updated_files = 0
    total_files = 0
    
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                file_path = os.path.join(root, file)
                total_files += 1
                if replace_swagger_annotations(file_path):
                    updated_files += 1
    
    return updated_files, total_files

def main():
    """主函数"""
    # 检查src/main/java目录是否存在
    java_dir = "src/main/java"
    if not os.path.exists(java_dir):
        print(f"错误: 目录 {java_dir} 不存在")
        sys.exit(1)
    
    print("开始替换Swagger注解为OpenAPI 3注解...")
    print(f"处理目录: {java_dir}")
    print("-" * 50)
    
    updated_files, total_files = process_directory(java_dir)
    
    print("-" * 50)
    print(f"处理完成!")
    print(f"总文件数: {total_files}")
    print(f"更新文件数: {updated_files}")
    
    if updated_files > 0:
        print("\n重要提醒:")
        print("1. 请检查更新后的注解是否正确")
        print("2. 某些复杂的注解可能需要手动调整")
        print("3. 建议运行编译测试确保无错误")

if __name__ == "__main__":
    main() 